package com.lalosoft.gastostarjetaweb.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class RedactarEmailServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger("RedactarEmailServlet");

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String destinatario = req.getParameter("to");
		if(!destinatario.equals("null")){
			if(destinatario.contains("<")){
				destinatario = getDestinatario(destinatario);
			}
		} else {
			destinatario = "";
		}
		String asunto = req.getParameter("asunto");
		
		log.log(Level.WARNING, "Destinatario parseado: " + destinatario);
		log.log(Level.WARNING, "Asunto posterior: " + asunto);
		
		req.setAttribute("to", destinatario);
		req.setAttribute("subject", asunto);
        RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/redactarEmail.jsp");
        requestDispatcher.forward(req, resp);
		
	}
	
	private static String getDestinatario(String destinatario){
		log.log(Level.WARNING, "Destinatario sin parsear: " + destinatario);
		int indexPicoAbrir = destinatario.indexOf("<");
		int indexPicoCerrar = destinatario.indexOf(">");
		String result = destinatario.substring(indexPicoAbrir + 1, indexPicoCerrar);
		return result;
	}
	
}
